function displayOrderItem(){
	var Tabs =getCurrentTable();
	createCategoryLeftmenu();
	createFavolateList();
	getCurrentPOSitemPosition();
	createOrderList();
	showorderList();
	calculateSumary();
	createtitle();
	$('[name=favorite]').find($('table')).first().show();
}

function createtitle(){
	var Tabs =getCurrentTable();
	if(Tabs == null)return;
	if($('[name=tabletitle]').children().size() == 0)
		$('[name=tabletitle]').append('<span style="color:#9b9d9a">'+titleTable+" "+Tabs.table.tableTitle +'</span>'+"<span>  <  </span>"+titleOrder);
}

function createCategoryLeftmenu(){
	$('.categoryleftitem').children().remove();
	var posItem =POSItemStructure.cats;
	$('.keeprightCatdetail').find('span').text(posItem.length);
	var text ="";
	var name ="name";
	for(var n = 0;n<posItem.length;n++){
		text+='<tr><td onclick="changePosItemPointer(this)" rifId="'+posItem[n].data.id+'" class="canclick"><span class="CategoryName">'+(n+1)+"."+'&nbsp;'+posItem[n].data.title+'</span><span class="CategoryAmt">'+posItem[n].items.length+'</span></td></tr>';
	}
	
	$('.categoryleftitem').append('<table>'+text+'</table>');
	var Tabs =getCurrentTable();
	var columns = null;
	if(Tabs.showCat == false ){
		$('.categoryleftitem:visible').hide();
		columns =8;
		createOrderList(columns);
	}else{
		$('.categoryleftitem').show();
		createOrderList(columns);
	}
}

function changePosItemPointer(e){
	var Tabs =getCurrentTable();
	if(Tabs != null){
		if($(e).offset().top <= $(".categoryleftitem").offset().top){
			var top = $(e).offset().top - $(".categoryleftitem table").not(".fixScrollItem table").offset().top;
			$(".categoryleftitem").animate({scrollTop: (top)},100);
		}
		else if($(e).offset().top+$(e).height() >= $(".categoryleftitem").offset().top+$(".categoryleftitem").height()){
			var top = $(e).offset().top + $(e).height() - $(".categoryleftitem").height() - $(".categoryleftitem").offset().top;
			$(".categoryleftitem").animate({scrollTop: (top)},100);
		}
		Tabs.posItemPointer =[];
		Tabs.posItemPointer.push($(e).attr('rifId'));
		createOrderList();
	}
}

function changePosInItemPointer(e){
	var Tabs =getCurrentTable();
	if(Tabs != null){
		if(Tabs.posItemPointer == null)Tabs.posItemPointer=[];
		Tabs.posItemPointer.push($(e).attr('rifId'));
		createOrderList();
	}
}

function getCurrentPOSitemPosition(){
	var Tabs =getCurrentTable();
	if(Tabs != null){
		var pointer = Tabs.posItemPointer;
		var positem = jQuery.extend({},POSItemStructure.cats);
		var positemAry = []
		for (var key in positem) {
			positemAry.push(positem[key]);
		}
		if(pointer==null||pointer.length==0)return;
		for(i=0;i<pointer.length;i++){
			var id = pointer[i];
			for(j=0;j<positemAry.length;j++)
				if(positemAry[j].data.id == id)
					positemAry = positemAry[j].items;
		}
		 return positemAry;
	}
}
function createOrderList(columns){
	var column = (columns>1)?columns:6;
	var pWidth=$('[name=show_positem]').width();
	var posItemDelAry =[];
	$('[name=show_positem]').children().remove();
	var Tabs =getCurrentTable();
	var posItem =[];
	var row =0;
	if(Tabs !=null){
		if(Tabs.posItemPointer!=null && Tabs.posItemPointer.length>0)
			posItem =[].concat(getCurrentPOSitemPosition());
			else posItem =[].concat(POSItemStructure.cats);
		row =Math.ceil(posItem.length/column);
	}else{
		posItem =[].concat(POSItemStructure.cats)
		row =Math.ceil(POSItemStructure.cats.length/column);
	}
	var text="";
	for(var x =0;x<row;x++){
		var i=0;
		text+='<tr>';
			for( i=0;i<posItem.length;i++){
				var active =(posItem[i].data.favourite>0)?"itemPosCatlikeicon":"itemPosCatNonelikeicon";
				if(i<column){
					if(posItem[i].type == "Item"){
						text +=	'<td><div class="productfoderitem canclick" rifId="'+posItem[i].data.id+'" onclick="AddtoOrderList(this)">'+
							'<div class="orderlistIcon '+active+'" onclick="makeFav(this)"></div>'+
							'<div>'+posItem[i].data.title+'</div></div></td>';
					}else if(posItem[i].type == "Cat"){
						text +=	'<td><div class="productfoderitem canclick" rifId="'+posItem[i].data.id+'" onclick="changePosInItemPointer(this)">'+
							'<div class="orderlistIcon fodertrapezium"></div>'+
							'<div>'+posItem[i].data.title+'</div></div></td>';
					}
					posItemDelAry.push(posItem[i].data.id);
				}else{
					for(var b=0;b<posItem.length;b++){
						for(var a =0;a<posItemDelAry.length;a++){
							if(posItem[b].data.id==posItemDelAry[a]){
								posItem.splice(b,1);
							}
						}
					}
					break;
				}
			}
		if(posItem.length-posItemDelAry.length != 0){
			 if((column-i)!=0){
				 for(var z = 0;z<column-Math.ceil(posItem.length/column);z++){
					 text+='<td name="elmTable">&nbsp;</td>';
				 }
			 }
		 }
		text+='</tr>';
	}
	$('[name=show_positem]').append('<table>'+text+'</table>');
	RenderBreadcrumb();
	FillActiveCategory();
}

function FillActiveCategory(){
	$(".categoryleftitem .fixScrollItem").remove();
	var list = getCurrentTable().posItemPointer;
	$(".categoryleftitem [rifid]").css("background-color","");
	$(".categoryleftitem [rifid]").css("color","");
	$(".categoryleftitem [rifid]").css("border-top","");
	$(".categoryleftitem [rifid]").css("border-bottom","");
	$(".categoryleftitem [rifid][isactive]").removeAttr("isactive");
	if(list!=null&&list.length>0){
		$(".categoryleftitem [rifid="+list[0]+"]").attr("isactive","true");
		$(".categoryleftitem [rifid="+list[0]+"]").css("background-color","#667FBA");
		$(".categoryleftitem [rifid="+list[0]+"]").css("color","#fff");
		$(".categoryleftitem [rifid="+list[0]+"]").css("border-top","1px solid #253B80");
		$(".categoryleftitem [rifid="+list[0]+"]").css("border-bottom","1px solid #253B80");
	}
}

function RenderBreadcrumb(){
	var list = getCurrentTable().posItemPointer;
	var breadcrumb = $(".productCatheader .catbaccomeheader");
	breadcrumb.find("span").not("span:first").remove();
	if(list!=null&&list.length>0){
		var ids = "";
		for(var _i=0;_i<list.length;_i++){
			var obj = getObjectFromSharedData(SharedData.Category,list[_i]);
			ids += "," + obj.id;
			breadcrumb.append("<span> > </span><span class='link' refid='"+ids.substr(1)+"' onclick='BreadcrumbClick(this)'>"+obj.title+"</span>");
		}
	}
}

function BreadcrumbClick(el){
	getCurrentTable().posItemPointer = $(el).attr("refid").split(",");
	createOrderList();
}

function makeFav(el,s){
	var itemid = $(el).parents("[rifid]").attr("rifid");
	if(itemid==null) itemid = $(el).parents(".favorateitem:first").attr("refid");
	var set = ($(el).is(".itemPosCatNonelikeicon"))? true:false;
	if(s!=null) set = s;
	simpleserviceWithError("/POSItemService",{func:"setFav",item:itemid,set:set},function(data){
		var objArray = JSON.parse(data);
		setFavWithRefresh(objArray.id,objArray.favourite);
	},function(data){
	},null);
}

function setFav(itemid,fav){
	var objItem = getObjectFromSharedData(SharedData.Item,itemid);
	objItem.favourite = fav;
	var itemcat = getPOSItem(POSItemStructure.cats,itemid);
	itemcat.data.favourite = fav;
	pushPOSFavItem();
	function getPOSItem(struct,itemId){
		var rs = null;
		for(var _i=0;_i<struct.length;_i++)
			if(struct[_i].data.id == itemId && struct[_i].type == "Item")
				return struct[_i];
			else
				if(struct[_i].items.length>0){
					rs = getPOSItem(struct[_i].items,itemId);
					if(rs!=null) return rs;
				}
		return rs;
	}
}
function setFavWithRefresh(itemid,fav){
	setFav(itemid,fav);
	createFavolateList();
	createOrderList();
}

function createFavolateList(){
	$('[name=favorateAmt]').text(POSItemStructure.fav.length);
	var favList="";
	$('[name=favolateItemList]').find(".favorateitem").remove();
	POSItemStructure.fav.sort(function(a, b) {return a.data.favourite - b.data.favourite})
	for(var i=0;i<POSItemStructure.fav.length;i++)
		$('[name=favolateItemList]').append('<div class="favorateitem canclick" refid="'+POSItemStructure.fav[i].data.id+'" onclick="AddtoOrderList(this)"><div class="orderlistIcon itemlikeicon" onclick="makeFav(this,false)"></div><span>'+POSItemStructure.fav[i].data.title+'</span></div>');
}

function createPOSbyProductCat(){
	var Tabs =getCurrentTable();
	Tabs.posItemPointer=[];
	createOrderList();
}

function AddtoOrderList(e){
	if($(event.target).is("[class*=itemPosCat][class*=likeicon]")) return;
	if($(event.target).hasClass("itemlikeicon")) return;
	var Tabs =getCurrentTable();
	if(Tabs != null){
		var itemId = $(e).attr('rifId');
		var favitem =$(e).attr('refId');
		if(Tabs.orderItemList == null)Tabs.orderItemList=[];
		
			var pointer = Tabs.posItemPointer;
			if(itemId!=null){ 
				var positem = jQuery.extend({},POSItemStructure.cats);
				var positemAry = [];
				for (var key in positem) {
					positemAry.push(positem[key]);
				}
				for(i=0;i<pointer.length;i++){
					var id = pointer[i];
					for(j=0;j<positemAry.length;j++)
						if(positemAry[j].data.id == id)
							positemAry = positemAry[j].items;
				}
			}
			else{
				if(POSItemStructure.fav != null){
					itemId =favitem;
					var posfavitem = jQuery.extend({},POSItemStructure.fav);
					var positemAry = [];
					for (var key in posfavitem) {
						positemAry.push(posfavitem[key]);
					}
				}
			}
			for(var n=0;n<positemAry.length;n++){
				if(positemAry[n].data.id == itemId){
					if(!checkforpushQty(itemId)){
						var obj={item:positemAry[n],Quantity:countQty(itemId)};
						Tabs.orderItemList.push(obj);
					}
					
				}
			}
	}
	showorderList();
}

function countQty(itemId){
	var Qty = 1;
	var Tabs =getCurrentTable();
	var itemList = Tabs.orderItemList ;
	for(var t=0;t<itemList.length;t++){
		if(itemList[t].item.data.id == itemId)
			Qty +=itemList[t].Quantity;
	}
	return Qty;
}
function checkforpushQty(itemId){
	var Tabs =getCurrentTable();
	var itemList = Tabs.orderItemList ;
	if(itemList.length != 0){
			for(var t=0;t<itemList.length;t++){
				if(itemList[t].item.data.id == itemId){
					itemList[t].Quantity+=1;
					return true;
				}
			}
			return false;
	}
}

function showorderList(){
	$('.orderlistbody').children().remove();
	$('[name=orderAmount]:visible').text("");
	var Tabs =getCurrentTable();
	var Text = "";
	var itemList = Tabs.orderItemList ;
	if(itemList == null){
		$('.orderlistbody').append('<div style="margin-top:50%"><div  class="orderlistIcon orderBookicon"></div><div name="additemText">'+titleAdditem+'</div></div>');
		return;
	} 
	for(var i=0;i<itemList.length;i++){
		var price = (SharedData.General.incloudetax)? itemList[i].item.data.price + itemList[i].item.data.totalTax : itemList[i].item.data.price;
		Text+='<tr name="setAttrinHover" refId="'+itemList[i].item.data.id+'"><td class="grytitle">'+(i+1)+'</td>'
		+'<td><div class="hidetext">'+itemList[i].item.data.title+'</div></td>'
		+'<td><div>'+toCurrencyString(price,false)+'</div></td>'
		+'<td><div><input type="text" value="'+itemList[i].Quantity+'" name="QtrItem" style="width:34px" onclick="numpad(this,null,orderFromNumpad)"></div></td>'
		+'<td><div class="orderlistIcon orderItembinIcon" name="orderbin" onclick="removeOrderedItem(this)"></div></td></tr>';
	}
	$('.orderlistbody').append('<table  name="orderlistTable">'+Text+'</table>');
	ForceNumericOnly($('.orderlistbody [name=QtrItem]'));
	$('[name=orderAmount]:visible').text("("+listAmt+' '+itemList.length+")");
	calculateSumary();
}

function removeOrderedItem(el){
	var tr = $(el).parents("tr:first");
	var items = getCurrentTable().orderItemList;
	var obj = getObjectFromDataIndexArray(items,["item","data","id"],tr.attr("refid"));
	items.splice(items.indexOf(obj),1);
	tr.remove();
	calculateSumary();
}

function orderFromNumpad(caller,num){
	var refid = $(caller).parents("tr:first").attr("refid");
	var obj = getObjectFromDataIndexArray(getCurrentTable().orderItemList,["item","data","id"],refid);
	if(obj!=null && num > 0){
		obj.Quantity = num;
		calculateSumary();
	}
}

function calculateSumary(){
	var Tabs =getCurrentTable();
	$('[name=orderItemprice]').html(toCurrencyString(0,false));
	if(Tabs==null)return;
	var sum=0;
	var itemList = Tabs.orderItemList ;
	if(itemList != null){
		for(var i=0;i<itemList.length;i++){
			var priceAndTax = calPriceAndTax(itemList[i].item.data);
			sum+= priceAndTax.totalPrice*itemList[i].Quantity;
		}
	}
	$('[name=orderItemprice]:visible').html(toCurrencyString(sum,false));
}

function hideProductCat(){
	var Tabs =getCurrentTable();
	Tabs.showCat = null;
	var columns = null;
	if($('.categoryleftitem').css('display') =='none'){
		$('.categoryleftitem').show();
		createOrderList(columns);
		Tabs.showCat = true;
	}
	else{
		Tabs.showCat = false;
		$('.categoryleftitem:visible').hide();
		 columns =8;
		createOrderList(columns);
	}
	
}

function SaveOrdertoEntity(){
	var Tabs = getCurrentTable();
	if(Tabs==null)return;
	delete Tabs.POSHistory;
	var orderitemAny =[];
	for(var i=0;i<Tabs.orderItemList.length;i++){
		var obj={};
		obj.id = Tabs.orderItemList[i].item.data.id;
		obj.q = Tabs.orderItemList[i].Quantity;
		orderitemAny.push(obj);
	}
	var PresId=(Tabs.OwnerTable!=null)?Tabs.OwnerTable.resId:null;
	var jsonString = JSON.stringify(orderitemAny);

	var link = "/POSgenerateOrderService?func=CreatePOSorderItem&orderitemAny="+jsonString+"&t="+Tabs.table.id+"&PresId="+PresId;
	simpleserviceWithArgs(link,null,SaveOrdertoEntitySuccess,PresId);
	waitingDialog();
}

function SaveOrdertoEntitySuccess(data,obj){
	var objArray = JSON.parse(data);
	if(objArray == null){
		simpleDialog("save fail!!",200);
		closeWaitingDialog();
	}else{
		var checkLogOut = checkSessionPOS(objArray);
		if(checkLogOut)
			return;
		if(objArray.PGuestId!=null)
			SharedData.POSReservationTable.push({id:objArray.PGuestId,tableId:objArray.TableId,Status:objArray.Status,haveOrder:objArray.haveOrder,money:objArray.money,Arrivel:objArray.Arrivel});
		var tab = getCurrentTable();
		tab.posresid = (obj!=null)? obj:objArray.PGuestId;
		tab.pagetitle = "orderlist";
		tab.OrderList = objArray.OrderList;
		var total = 0;
		for(var i=0;i<tab.OrderList.length;i++)
			for(var j=0;j<tab.OrderList[i].items.length;j++){
				tab.OrderList[i].items[j].refItem = getObjectFromSharedData(SharedData.Item,getCurrentTable().OrderList[i].items[j].item);
				var item = tab.OrderList[i].items[j];
				if(!item.status) continue;
				var priceAndTax = calPriceAndTaxWithQuantity(item);
				total += priceAndTax.displayPriceTotal;
			}
		tab.activeOrderId = tab.OrderList[tab.OrderList.length-1].id;
		var res = getObjectFromSharedData(SharedData.POSReservationTable,tab.posresid);
		res.money = total;
		switchTab($("#tabs .tab.active"));
		if(tab.OwnerTable == null){
		tab.OwnerTable={};
		tab.OwnerTable.resId=objArray.PGuestId;
		tab.OwnerTable.Name=null;
		}
		createTableblock(null);
	}
}
